﻿using EFCoreDemo.Models;
using Microsoft.EntityFrameworkCore;

namespace EFCoreDemo.Services;

public class DemoService : IDemoService {
    private DemoContext _demoContext;

    public DemoService(DemoContext demoContext) {
        _demoContext = demoContext;
    }

    public async Task<DemoModel> AddAsync(DemoModel demoModel) {
        var modelEntry = await _demoContext.AddAsync(demoModel);
        await _demoContext.SaveChangesAsync();
        return modelEntry.Entity;
    }

    public async Task<DemoModel> UpdateAsync(DemoModel demoModel) {
        var modelToUpdate =
            await _demoContext.DemoModels.FirstOrDefaultAsync(p =>
                p.Id == demoModel.Id);
        modelToUpdate.Name = demoModel.Name;
        await _demoContext.SaveChangesAsync();
        return modelToUpdate;
    }

    public async Task<DemoModel> DeleteAsync(int id) {
        var modelToDelete =
            await _demoContext.DemoModels.FirstOrDefaultAsync(p => p.Id == id);
        _demoContext.Remove(modelToDelete);
        await _demoContext.SaveChangesAsync();
        return modelToDelete;
    }

    public async Task<IEnumerable<DemoModel>> ListAsync() {
        return await _demoContext.DemoModels.ToListAsync();
    }
}